<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="所属省" prop="province">
        <el-input
          v-model="queryParams.province"
          placeholder="请输入所属省"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属市" prop="city">
        <el-input
          v-model="queryParams.city"
          placeholder="请输入所属市"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option label="上架" value="0" />
          <el-option label="下架" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="操作时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['demo:shop:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['demo:shop:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['demo:shop:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="productList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="商品ID" align="center" prop="productId" />
      <el-table-column label="所属省" align="center" prop="province" :show-overflow-tooltip="true" />
      <el-table-column label="所属市" align="center" prop="city" :show-overflow-tooltip="true" />
      <el-table-column label="代理商" align="center" prop="agent" :show-overflow-tooltip="true" />
      <el-table-column label="商品名称" align="center" prop="productName" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <el-link type="primary" @click="handlePreview(scope.row)">{{ scope.row.productName }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="商品类型" align="center" prop="productType" :show-overflow-tooltip="true" />
      <el-table-column label="金额" align="center" prop="amount" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag v-if="scope.row && scope.row.status === '0'" type="success">上架</el-tag>
          <el-tag v-else-if="scope.row && scope.row.status === '1'" type="danger">下架</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="所属人" align="center" prop="owner" :show-overflow-tooltip="true" />
      <el-table-column label="操作时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span v-if="scope.row && scope.row.createTime">{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['demo:shop:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['demo:shop:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="所属省" prop="province">
              <el-select v-model="form.province" placeholder="请选择所属省" @change="handleProvinceChange" style="width: 100%">
                <el-option
                  v-for="item in provinceOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属市" prop="city">
              <el-select v-model="form.city" placeholder="请选择所属市" style="width: 100%">
                <el-option
                  v-for="item in cityOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="代理商" prop="agent">
              <el-autocomplete
                v-model="form.agent"
                :fetch-suggestions="queryAgentSearch"
                placeholder="请输入代理商"
                style="width: 100%"
              ></el-autocomplete>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="金额" prop="amount">
              <el-input v-model="form.amount" placeholder="请输入金额（保留2位小数）" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="商品名称" prop="productName">
              <el-input v-model="form.productName" placeholder="请输入商品名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="商品类型" prop="productType">
              <el-radio-group v-model="form.productType">
                <el-radio label="类型1">类型1</el-radio>
                <el-radio label="类型2">类型2</el-radio>
                <el-radio label="类型3">类型3</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="商品颜色" prop="productColor">
              <el-checkbox-group v-model="form.productColorList">
                <el-checkbox label="颜色1">颜色1</el-checkbox>
                <el-checkbox label="颜色2">颜色2</el-checkbox>
                <el-checkbox label="颜色3">颜色3</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="发布时间" prop="publishTime">
              <el-date-picker
                v-model="form.publishTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="请选择发布时间"
                style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%">
                <el-option label="上架" value="0"></el-option>
                <el-option label="下架" value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="所属人" prop="owner">
              <el-input v-model="form.owner" placeholder="请输入所属人" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="商品描述">
              <editor v-model="form.description" :min-height="192"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="预览图">
              <image-upload v-model="form.imageUrls" :limit="3"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider content-position="left">联系方式</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddContact">添加</el-button>
          </el-col>
        </el-row>
        <el-table :data="form.contactList" :row-class-name="rowContactIndex" @selection-change="handleContactSelectionChange">
          <el-table-column label="序号" type="index" width="50" align="center">
            <template slot-scope="scope">
              <span>{{scope.$index + 1}}</span>
            </template>
          </el-table-column>
          <el-table-column label="姓名" prop="contactName" width="200">
            <template slot-scope="scope">
              <el-form-item :prop="'contactList.' + scope.$index + '.contactName'" :rules="contactRules.contactName">
                <el-input v-model="scope.row.contactName" placeholder="请输入姓名（汉字，最多5个字）" maxlength="5" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="手机" prop="phone" width="200">
            <template slot-scope="scope">
              <el-form-item :prop="'contactList.' + scope.$index + '.phone'" :rules="contactRules.phone">
                <el-input v-model="scope.row.phone" placeholder="请输入手机" maxlength="11" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="邮箱" prop="email" width="250">
            <template slot-scope="scope">
              <el-form-item :prop="'contactList.' + scope.$index + '.email'" :rules="contactRules.email">
                <el-input v-model="scope.row.email" placeholder="请输入邮箱" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-button
                type="text"
                icon="el-icon-delete"
                @click="handleDeleteContact(scope.$index, scope.row)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容（最多255个字）" maxlength="255" show-word-limit />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">保 存</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 预览对话框 -->
    <el-dialog title="商品信息预览" :visible.sync="openPreview" width="900px" append-to-body>
      <el-form ref="previewForm" :model="previewData" label-width="100px" disabled>
        <el-row>
          <el-col :span="12">
            <el-form-item label="所属省">
              <el-input v-model="previewData.province" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属市">
              <el-input v-model="previewData.city" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="代理商">
              <el-input v-model="previewData.agent" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="金额">
              <el-input v-model="previewData.amount" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="商品名称">
              <el-input v-model="previewData.productName" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="商品类型">
              <el-input v-model="previewData.productType" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="商品颜色">
              <el-input v-model="previewData.productColor" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="发布时间">
              <el-input v-model="previewData.publishTime" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-tag v-if="previewData.status === '0'" type="success">上架</el-tag>
              <el-tag v-else-if="previewData.status === '1'" type="danger">下架</el-tag>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="所属人">
              <el-input v-model="previewData.owner" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="商品描述">
              <div v-html="previewData.description" style="border: 1px solid #dcdfe6; padding: 10px; min-height: 100px;"></div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="预览图">
              <div v-if="previewData.imageList && previewData.imageList.length > 0">
                <el-image
                  v-for="(img, index) in previewData.imageList"
                  :key="index"
                  :src="img.imageUrl"
                  :preview-src-list="previewData.imageList.map(item => item.imageUrl)"
                  style="width: 100px; height: 100px; margin-right: 10px;"
                ></el-image>
              </div>
              <span v-else>无</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider content-position="left">联系方式</el-divider>
        <el-table :data="previewData.contactList" border>
          <el-table-column label="序号" type="index" width="50" align="center" />
          <el-table-column label="姓名" prop="contactName" align="center" />
          <el-table-column label="手机" prop="phone" align="center" />
          <el-table-column label="邮箱" prop="email" align="center" />
        </el-table>
        <el-row style="margin-top: 20px;">
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="previewData.remark" type="textarea" :rows="3" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="openPreview = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listProduct, getProduct, delProduct, addProduct, updateProduct } from "@/api/demo/product";
import { getProvinces, getCitiesByProvince } from "@/utils/province-city";

export default {
  name: "Shop",
  data() {
    // 验证姓名（必须是汉字，最多5个字）
    const validateContactName = (rule, value, callback) => {
      if (value === '' || value === null || value === undefined) {
        callback();
      } else if (!/^[\u4e00-\u9fa5]{1,5}$/.test(value)) {
        callback(new Error('姓名必须是汉字，最多5个字'));
      } else {
        callback();
      }
    };
    // 验证手机号
    const validatePhone = (rule, value, callback) => {
      if (value === '' || value === null || value === undefined) {
        callback();
      } else if (!/^1[3-9]\d{9}$/.test(value)) {
        callback(new Error('请输入有效的手机号码'));
      } else {
        callback();
      }
    };
    // 验证邮箱
    const validateEmail = (rule, value, callback) => {
      if (value === '' || value === null || value === undefined) {
        callback();
      } else if (!/^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/.test(value)) {
        callback(new Error('请输入有效的邮箱地址'));
      } else {
        callback();
      }
    };
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品信息表格数据
      productList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示预览对话框
      openPreview: false,
      // 日期范围
      dateRange: [],
      // 省份列表
      provinceOptions: [],
      // 城市列表
      cityOptions: [],
      // 代理商列表（用于联想输入）
      agentOptions: [],
      // 表单参数
      form: {},
      // 预览数据
      previewData: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        province: null,
        city: null,
        productName: null,
        status: null,
      },
      // 表单校验
      rules: {
        province: [
          { required: true, message: "所属省不能为空", trigger: "change" }
        ],
        city: [
          { required: true, message: "所属市不能为空", trigger: "change" }
        ],
        agent: [
          { required: true, message: "代理商不能为空", trigger: "blur" }
        ],
        productName: [
          { required: true, message: "商品名称不能为空", trigger: "blur" },
          { max: 20, message: "商品名称不能超过20个字", trigger: "blur" }
        ],
        amount: [
          { required: true, message: "金额不能为空", trigger: "blur" },
          { pattern: /^(([1-9]\d*)|\d)(\.\d{1,2})?$/, message: "金额格式不正确，最多保留2位小数", trigger: "blur" }
        ],
        publishTime: [
          { required: true, message: "发布时间不能为空", trigger: "change" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ],
        remark: [
          { max: 255, message: "备注最多输入255个字", trigger: "blur" }
        ]
      },
      // 联系方式校验规则
      contactRules: {
        contactName: [
          { validator: validateContactName, trigger: "blur" }
        ],
        phone: [
          { validator: validatePhone, trigger: "blur" }
        ],
        email: [
          { validator: validateEmail, trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.loadProvinces();
    this.loadAgents();
  },
  methods: {
    /** 加载省份列表 */
    loadProvinces() {
      this.provinceOptions = getProvinces();
    },
    /** 省份改变时加载城市列表 */
    handleProvinceChange(value) {
      this.form.city = null;
      this.cityOptions = getCitiesByProvince(value);
    },
    /** 加载代理商列表（用于联想输入） */
    loadAgents() {
      // 从已有商品中提取代理商列表
      listProduct({}).then(response => {
        const agents = new Set();
        if (response.rows) {
          response.rows.forEach(item => {
            if (item.agent) {
              agents.add(item.agent);
            }
          });
        }
        this.agentOptions = Array.from(agents);
      });
    },
    /** 代理商搜索 */
    queryAgentSearch(queryString, cb) {
      const results = queryString ? this.agentOptions.filter(item => {
        return item.toLowerCase().indexOf(queryString.toLowerCase()) === 0;
      }).map(item => ({ value: item })) : this.agentOptions.map(item => ({ value: item }));
      cb(results);
    },
    /** 查询商品信息列表 */
    getList() {
      this.loading = true;
      listProduct(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.productList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        productId: null,
        province: null,
        city: null,
        agent: null,
        productName: null,
        productType: null,
        productColor: null,
        productColorList: [],
        status: "0",
        owner: null,
        description: null,
        amount: null,
        publishTime: null,
        imageUrls: null,
        contactList: [],
        remark: null
      };
      this.cityOptions = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.productId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商品信息";
    },
    /** 预览按钮操作 */
    handlePreview(row) {
      this.reset();
      const productId = row.productId;
      getProduct(productId).then(response => {
        this.previewData = response.data;
        // 处理图片列表
        if (!this.previewData.imageList) {
          this.previewData.imageList = [];
        }
        // 处理联系方式列表
        if (!this.previewData.contactList) {
          this.previewData.contactList = [];
        }
        this.openPreview = true;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const productId = row.productId || this.ids
      getProduct(productId).then(response => {
        this.form = response.data;
        // 处理商品颜色
        if (this.form.productColor) {
          this.form.productColorList = this.form.productColor.split(',');
        } else {
          this.form.productColorList = [];
        }
        // 处理图片列表
        if (this.form.imageList && this.form.imageList.length > 0) {
          this.form.imageUrls = this.form.imageList.map(item => item.imageUrl).join(',');
        } else {
          this.form.imageUrls = null;
        }
        // 处理联系方式列表
        if (!this.form.contactList) {
          this.form.contactList = [];
        }
        // 加载对应省份的城市列表
        if (this.form.province) {
          this.cityOptions = getCitiesByProvince(this.form.province);
        }
        this.open = true;
        this.title = "修改商品信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 处理商品颜色
          this.form.productColor = this.form.productColorList ? this.form.productColorList.join(',') : null;
          // 处理图片列表
          if (this.form.imageUrls) {
            const imageUrls = this.form.imageUrls.split(',');
            this.form.imageList = imageUrls.map((url, index) => {
              return {
                imageUrl: url,
                sortOrder: index
              };
            });
          } else {
            this.form.imageList = [];
          }

          if (this.form.productId != null) {
            updateProduct(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addProduct(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const productIds = row.productId || this.ids;
      this.$modal.confirm('是否确认删除商品信息编号为"' + productIds + '"的数据项？').then(function() {
        return delProduct(productIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 联系方式序号 */
    rowContactIndex({ row, rowIndex }) {
      row.index = rowIndex;
    },
    /** 联系方式添加按钮操作 */
    handleAddContact() {
      let obj = {};
      obj.contactName = "";
      obj.phone = "";
      obj.email = "";
      this.form.contactList.push(obj);
    },
    /** 联系方式删除按钮操作 */
    handleDeleteContact(index, row) {
      this.form.contactList.splice(index, 1);
    },
    /** 联系方式多选框选中数据 */
    handleContactSelectionChange(selection) {
      this.checkedContact = selection.map(item => item.index)
    }
  }
};
</script>
